<template>
  <div class="platform-container">
    <!-- 上半部分：获取二维码 -->
    <el-card class="qr-section">
      <template #header>
        <div class="section-header">
          <div class="title">
            <el-icon><Link /></el-icon>
            <span>新微信登录</span>
          </div>
          <!-- 允许拥有查看平台权限的用户获取二维码（普通用户可用） -->
          <el-button 
            v-permission="Permission.VIEW_PLATFORMS"
            type="primary" 
            @click="handleGetQRCode" 
            :loading="loading"
          >
            <el-icon><Promotion /></el-icon>
            获取登录二维码
          </el-button>
        </div>
      </template>

      <div class="section-description">
        扫描二维码登录新的微信账号，支持多账号管理
      </div>
    </el-card>

    <!-- 下半部分：用户列表 -->
    <el-card class="user-list-section">
      <template #header>
        <div class="section-header">
          <span>已登录账号</span>
          <!-- 所有有查看平台权限的用户都可以刷新列表 -->
          <div class="button-group">
            <el-button type="primary" @click="refreshUserList">
              <el-icon><Refresh /></el-icon>
              刷新列表
            </el-button>
            <el-button type="primary" @click="create_user">
              <el-icon><Refresh /></el-icon>
              同步账号
            </el-button>
          </div>
        </div>
      </template>

      <!-- 批量操作按钮 -->
      <div class="batch-actions" style="margin-bottom: 12px; display: flex; gap: 10px;">
        <el-button type="primary" :disabled="!selectedUsers.length" @click="batchSyncFriends">批量同步微信好友</el-button>
        <el-button type="primary" :disabled="!selectedUsers.length" @click="batchRefreshStatus">批量刷新状态</el-button>
        <el-button type="primary" :disabled="!selectedUsers.length" @click="batchWakeupLogin">批量唤醒登录</el-button>
      </div>

      <!-- 加载状态 -->
      <div v-if="listLoading" class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>

      <!-- 空状态 -->
      <el-empty v-else-if="!userList.length" description="暂无登录账号" />

      <!-- 用户列表 -->
      <el-table v-else :data="userList" style="width: 100%" @selection-change="handleUserSelectionChange" ref="userTableRef">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="nickname" label="昵称" min-width="120" />
        <el-table-column prop="device_id" label="微信ID" min-width="120" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="login_at" label="登录时间" min-width="180">
          <template #default="{ row }">
            {{ formatDate(row.login_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalOnlineTime" label="总计在线时长" min-width="120">
          <template #default="{ row }">
            {{ row.totalOnlineTime || '0天0时0分' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-button type="danger" link @click="handleWXfriendSync(row)">
              同步微信好友
            </el-button>
            <el-button 
              type="primary" 
              link 
              :loading="row.refreshing"
              @click="handleRefreshStatus(row)"
            >
              刷新状态
            </el-button>
            <!-- 只有有管理平台权限的用户才能唤醒登录 -->
            <el-button 
              v-permission="Permission.MANAGE_PLATFORMS"
              type="success" 
              link 
              :loading="row.waking"
              :disabled="row.status === 1"
              @click="handleWakeUpLogin(row)"
            >
              唤醒登录
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 二维码弹窗 -->
    <el-dialog
      v-model="qrDialogVisible"
      title="微信扫码登录"
      width="400px"
      center
      align-center
    >
      <div class="qr-container">
        <div v-if="qrImg" class="qr-image">
          <img :src="qrImg" alt="微信二维码" />
          <p class="qr-tip">请使用微信扫描二维码登录</p>
          <p class="qr-expire">二维码有效期5分钟，过期请刷新</p>
        </div>
        <div v-else-if="errorMsg" class="error-message">
          {{ errorMsg }}
          <el-button type="primary" size="small" @click="handleGetQRCode" class="retry-button">
            重试
          </el-button>
        </div>
        <div v-else class="loading-message">
          <el-icon class="is-loading"><Loading /></el-icon>
          正在获取二维码...
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, onUnmounted } from 'vue'
import { Link, Promotion, Loading, Refresh } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Permission } from '@/utils/permission'

// 缓存键：用于在页面切换后保留每个设备的累计在线时长
const ONLINE_TIME_CACHE_KEY = 'platform_online_time_cache'

type OnlineCacheMap = Record<string, { totalOnlineTime: string; lastUpdateTime: number }>

const loadOnlineCache = (): OnlineCacheMap => {
  try {
    return JSON.parse(localStorage.getItem(ONLINE_TIME_CACHE_KEY) || '{}') as OnlineCacheMap
  } catch {
    return {}
  }
}

const saveOnlineCache = (map: OnlineCacheMap) => {
  localStorage.setItem(ONLINE_TIME_CACHE_KEY, JSON.stringify(map))
}

const upsertOnlineCache = (authKey: string, totalOnlineTime: string, lastUpdateTime: number) => {
  const map = loadOnlineCache()
  map[authKey] = { totalOnlineTime, lastUpdateTime }
  saveOnlineCache(map)
}

// 更新用户接口定义
interface WxUser {
  nickname: string
  device_id: string
  auth_key: string
  status: number  // 0: 离线, 1: 在线
  login_at: string
  refreshing?: boolean
  waking?: boolean
  totalOnlineTime?: string  // 总在线时长
  lastUpdateTime?: number   // 上次更新时间戳
}

const loading = ref(false)
const listLoading = ref(false)
const qrDialogVisible = ref(false)
const qrImg = ref('')
const errorMsg = ref('')
const userList = ref<WxUser[]>([])
const qrId = ref('')
let pollTimer: number | null = null
let onlineTimer: number | null = null  // 在线时长计时器
const selectedUsers = ref<WxUser[]>([])
const userTableRef = ref()

const handleUserSelectionChange = (selection: WxUser[]) => {
  selectedUsers.value = selection
}

const batchSyncFriends = async () => {
  if (!selectedUsers.value.length) return
  await Promise.all(selectedUsers.value.map(user => handleWXfriendSync(user)))
  ElMessage.success('批量同步完成')
}

const batchRefreshStatus = async () => {
  if (!selectedUsers.value.length) return
  await Promise.all(selectedUsers.value.map(user => handleRefreshStatus(user)))
  ElMessage.success('批量刷新完成')
}

const batchWakeupLogin = async () => {
  if (!selectedUsers.value.length) return
  await Promise.all(selectedUsers.value.map(user => handleWakeUpLogin(user)))
  ElMessage.success('批量唤醒完成')
}

// 格式化日期
const formatDate = (dateStr: string) => {
  const date = new Date(dateStr)
  return date.toLocaleString()
}

// 格式化在线时长
const formatOnlineTime = (days: number, hours: number, minutes: number) => {
  let result = ''
  if (days > 0) result += `${days}天`
  if (hours > 0) result += `${hours}时`
  result += `${minutes}分`
  return result
}

// 更新在线用户的时长
const updateOnlineTime = () => {
  let cacheChanged = false
  const cache = loadOnlineCache()
  userList.value.forEach(user => {
    if (user.status === 1 && user.lastUpdateTime) {
      const now = Date.now()
      const diffMinutes = Math.floor((now - user.lastUpdateTime) / (1000 * 60))
      
      if (diffMinutes > 0) {
        // 解析当前总在线时长
        const timeMatch = user.totalOnlineTime?.match(/(\d+)天(\d+)时(\d+)分/)
        if (timeMatch) {
          let days = parseInt(timeMatch[1])
          let hours = parseInt(timeMatch[2])
          let minutes = parseInt(timeMatch[3]) + diffMinutes

          // 处理进位
          if (minutes >= 60) {
            hours += Math.floor(minutes / 60)
            minutes = minutes % 60
          }
          if (hours >= 24) {
            days += Math.floor(hours / 24)
            hours = hours % 24
          }

          user.totalOnlineTime = formatOnlineTime(days, hours, minutes)
          user.lastUpdateTime = now

          // 写入缓存，保证切换页面后仍能恢复
          cache[user.auth_key] = { totalOnlineTime: user.totalOnlineTime, lastUpdateTime: user.lastUpdateTime }
          cacheChanged = true
        }
      }
    }
  })
  if (cacheChanged) saveOnlineCache(cache)
}

const handleWXfriendSync = async (user: WxUser) => {
  try {
    const response = await axios.post('/wx_users/sync_friends', {
      device_id: user.device_id,
      auth_key: user.auth_key
    })
    if (response.data.code === 200) {
      ElMessage.success('同步成功')
    } else {
      ElMessage.error(response.data.message)
    }
  } catch (error) {
    ElMessage.error('同步失败')
  }
}
// 启动在线时长计时器
const startOnlineTimer = () => {
  if (onlineTimer) clearInterval(onlineTimer)
  onlineTimer = window.setInterval(updateOnlineTime, 60000) // 每分钟更新一次
}

// 停止在线时长计时器
const stopOnlineTimer = () => {
  if (onlineTimer) {
    clearInterval(onlineTimer)
    onlineTimer = null
  }
}

// 获取用户列表
const getUserList = async () => {
  listLoading.value = true
  try {
    const response = await axios.get('/wx_users', { params: { is_rag: false } })
    if (response.data.code === 200) {
      // 初始化每个用户的总在线时长
      const cache = loadOnlineCache()
      userList.value = response.data.data.map((user: WxUser) => {
        // 保留已缓存的总在线时长和最后更新时间（切换页面也不丢）
        const cached = cache[user.auth_key]
        return {
          ...user,
          totalOnlineTime: cached?.totalOnlineTime || '0天0时0分',
          lastUpdateTime: cached?.lastUpdateTime || (user.status === 1 ? Date.now() : undefined)
        }
      })
    } else {
      ElMessage.error(response.data.msg || '获取用户列表失败')
    }
  } catch (error: any) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败：' + (error.response?.data?.msg || error.message))
  } finally {
    listLoading.value = false
  }
}

// 刷新用户列表
const refreshUserList = () => {
  getUserList()
}

//同步更新创建用户
const create_user = async () => {
  try {
    const response = await axios.post(`/wx_users`, {
      auth_key: qrId.value
    })
    console.log('创建用户响应:', response.data)
    if (response.data.code === 200) {
      ElMessage.success('用户创建成功')
      return { success: true }
    } else {
      console.error('创建用户失败:', response.data.msg)
      ElMessage.error(response.data.msg || '创建用户失败')
      return { success: false }
    }
  }
  catch (error: any) {
    console.error('创建用户失败:', error)
    ElMessage.error('创建用户失败：' + (error.response?.data?.msg || error.message))
    return { success: false }
  }
}

// 获取二维码
const handleGetQRCode = async () => {
  qrDialogVisible.value = true
  loading.value = true
  errorMsg.value = ''
  qrImg.value = ''
  qrId.value = ''
  stopPolling() // 防止多次点击重复轮询
  
  try {
    const res = await axios.get('/GetLoginQrCodeNew',{timeout: 60000})
    console.log('获取二维码返回数据:', res.data)
    if (res.data.code === 200 && res.data.data) {
      if (res.data.data.QrCodeUrl) {
        qrImg.value = res.data.data.QrCodeUrl
        if (res.data.data.Key) {
          qrId.value = res.data.data.Key
          console.log('设置二维码ID:', qrId.value)
          startPolling() // 开始轮询
        } else {
          console.error('二维码ID不存在:', res.data)
          errorMsg.value = '获取二维码ID失败，请稍后重试'
        }
      } else {
        errorMsg.value = '获取二维码失败，请稍后重试'
      }
    } else {
      errorMsg.value = res.data.msg || '获取二维码失败，请稍后重试'
    }
  } catch (error: any) {
    console.error('请求错误:', error)
    errorMsg.value = '网络请求失败，请检查网络连接'
  } finally {
    loading.value = false
  }
}

// 刷新用户状态
const handleRefreshStatus = async (user: WxUser) => {
  user.refreshing = true
  try {
    const response = await axios.get(`/wx_users/${user.auth_key}/refresh`,{timeout: 30000})
    console.log('刷新状态接口返回数据:', response.data)
    
    if (response.data.code === 200) {
      // 尝试从多个可能的位置获取 totalOnline
      let totalOnline = null as string | null
      
      if (response.data.totalOnline) {
        totalOnline = response.data.totalOnline
      } else {
        const responseStr = JSON.stringify(response.data)
        const match = responseStr.match(/"totalOnline"\s*:\s*"([^"]+)"/)
        if (match && match[1]) {
          totalOnline = match[1]
        }
      }
      if (totalOnline) {
        // 解析天、时、分
        const daysMatch = totalOnline.match(/(\d+)天/)
        const hoursMatch = totalOnline.match(/(\d+)时/)
        const minutesMatch = totalOnline.match(/(\d+)分/)
        
        const days = daysMatch ? parseInt(daysMatch[1]) : 0
        const hours = hoursMatch ? parseInt(hoursMatch[1]) : 0
        const minutes = minutesMatch ? parseInt(minutesMatch[1]) : 0
        
        // 更新用户数据（以后按分钟自动累加）
        user.totalOnlineTime = formatOnlineTime(days, hours, minutes)
        user.lastUpdateTime = Date.now()
        // 同步缓存，保证页面切换不丢
        upsertOnlineCache(user.auth_key, user.totalOnlineTime, user.lastUpdateTime)
      } else {
        console.warn('未找到总在线时长数据')
      }
      
      ElMessage.success('状态刷新成功')
    } else {
      ElMessage.error(response.data.msg || '刷新状态失败')
    }
  } catch (error: any) {
    console.error('刷新状态失败:', error)
    ElMessage.error('刷新状态失败：' + (error.response?.data?.msg || error.message))
  } finally {
    user.refreshing = false
  }
}

// 获取状态类型
const getStatusType = (status: number): '' | 'success' | 'warning' | 'danger' => {
  switch (status) {
    case 1:
      return 'success'
    case 0:
      return 'danger'
    default:
      return ''
  }
}

// 获取状态文本
const getStatusText = (status: number): string => {
  return status === 1 ? '在线' : '离线'
}

// 唤醒微信登录
const handleWakeUpLogin = async (user: WxUser) => {
  user.waking = true
  try {
    const response = await axios.get(`/wx_users/${user.auth_key}/wake`,{timeout: 30000})
    if (response.data.code === 200) {
      ElMessage.success('唤醒登录成功')
      await getUserList()
    } else {
      ElMessage.error(response.data.msg || '唤醒登录失败')
    }
  } catch (error: any) {
    console.error('唤醒登录失败:', error)
    ElMessage.error('唤醒登录失败：' + (error.response?.data?.msg || error.message))
  } finally {
    user.waking = false
  }
}

// 实现轮询相关方法
const startPolling = () => {
  stopPolling()
  if (!qrId.value) return
  console.log('开始轮询检查二维码状态，qrId:', qrId.value)
  pollTimer = window.setInterval(checkQrStatus, 2000)
}

const stopPolling = () => {
  if (pollTimer) {
    clearInterval(pollTimer)
    pollTimer = null
    console.log('停止轮询')
  }
}

const checkQrStatus = async () => {
  if (!qrId.value) return
  console.log('检查二维码状态:', qrId.value)
  try {
    const res = await axios.get(`/GetLoginQrCodeNew/status/${qrId.value}`)
    console.log('二维码状态返回:', res.data)
    if (res.data.code === 200 && res.data.data) {
      const status = res.data.data.state
      console.log('二维码状态:', status)
      
      switch (status) {
        case 0:
          break
        case 1:
          break
        case 2:
          stopPolling()
          qrDialogVisible.value = false
          ElMessage.success('扫码登录成功，正在添加用户...')
          const authKey = qrId.value
          console.log('使用qrId作为auth_key:', authKey)
          const createResult = await create_user()
          if (createResult.success) {
            await getUserList()
          }
          break
        case 3:
          stopPolling()
          errorMsg.value = '二维码已过期，请重新获取'
          break
        default:
          break
      }
    } else {
      console.error('获取二维码状态失败:', res.data.msg || '未知错误')
    }
  } catch (error: any) {
    console.error('检查二维码状态失败:', error.message || error)
  }
}

// 弹窗关闭时停止轮询
watch(qrDialogVisible, (val) => {
  if (!val) stopPolling()
})

// 页面加载时获取用户列表并启动计时器
onMounted(() => {
  getUserList()
  startOnlineTimer()
})

// 页面卸载时清理计时器（缓存已在每次更新时写入）
onUnmounted(() => {
  stopOnlineTimer()
  stopPolling()
})
</script>

<style scoped lang="scss">
.platform-container {
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 24px;

  .qr-section, .user-list-section {
    .section-header {
      display: flex;
      align-items: center;
      gap: 8px;

      .title {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 16px;
        font-weight: 500;

        .el-icon {
          font-size: 18px;
        }
      }
    }
  }

  .user-list-section {
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      span {
        margin-right: 16px; // 标题和第一个按钮的距离
      }
      .button-group {
        display: flex;
        gap: 8px;
      }
    }
  }

  .section-description {
    color: #666;
    margin: 16px 0;
  }

  .loading-container {
    padding: 20px 0;
  }

  .qr-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;

    .qr-image {
      text-align: center;

      img {
        max-width: 280px;
        height: auto;
        border: 1px solid #ebeef5;
        border-radius: 4px;
        padding: 10px;
      }

      .qr-tip {
        margin-top: 16px;
        color: #666;
        font-size: 14px;
      }

      .qr-expire {
        margin-top: 8px;
        color: #909399;
        font-size: 12px;
      }
    }

    .error-message {
      color: #f56c6c;
      text-align: center;

      .retry-button {
        margin-top: 12px;
      }
    }

    .loading-message {
      display: flex;
      align-items: center;
      gap: 8px;
      color: #666;

      .el-icon {
        font-size: 20px;
      }
    }
  }
}
</style>